<template>
  <div class="goods-sku">
    <dl v-for="(spec, index) in goods.specs" :key="index">
      <dt>{{ spec.name }}</dt>
      <dd>
        <template v-for="btnObj in spec.values" :key="btnObj.name">
          <img
            v-if="btnObj.picture"
            :src="btnObj.picture"
            alt=""
            :class="{
              disabled: btnObj.disabled,
              selected: btnObj.selected
            }"
            @click="changeSku(btnObj, spec)"
          />
          <span
            v-else
            :class="{
              disabled: btnObj.disabled,
              selected: btnObj.selected
            }"
            @click="changeSku(btnObj, spec)"
            >{{ btnObj.name }}</span
          >
        </template>
      </dd>
    </dl>
  </div>
</template>
<script>
import bwPowerSet from '@/vendor/power-set'
const spliter = '🍕'

const getPathMap = (skus) => {
  const pathMap = {}
  skus.forEach((sku) => {
    if (sku.inventory > 0) {
      const arr = sku.specs.map((btnObj) => btnObj.valueName)
      const bwArr = bwPowerSet(arr)
      bwArr.forEach((bw) => {
        const key = bw.join(spliter)
        if (pathMap[key]) {
          pathMap[key].push(sku.id)
        } else {
          pathMap[key] = [sku.id]
        }
      })
    }
  })
  return pathMap
}

const updateDisabledStatus = (specs, pathMap) => {
  specs.forEach((spec, i) => {
    spec.values.forEach((btnObj) => {
      /* const key = btnObj.name
      if (pathMap[key]) {
        btnObj.disabled = false
      } else {
        btnObj.disabled = true
      } */
      if (btnObj.selected) return
      const origin = getSelectedSpec(specs)
      origin[i] = btnObj.name
      const key = origin.filter((v) => v).join(spliter)
      if (pathMap[key]) {
        btnObj.disabled = false
      } else {
        btnObj.disabled = true
      }
    })
  })
}

const getSelectedSpec = (specs) => {
  const arr = []
  specs.forEach((spec, i) => {
    const btnObj = spec.values.find((btnObj) => btnObj.selected)
    if (btnObj) {
      arr[i] = btnObj.name
    } else {
      arr[i] = undefined
    }
  })
  return arr
}

const initDefaultSelected = (goods, skuId) => {
  const sku = goods.skus.find((sku) => sku.id === skuId)
  if (!sku) return
  goods.specs.forEach((spec, i) => {
    spec.values.forEach((btnObj) => {
      btnObj.selected = btnObj.name === sku.specs[i].valueName
    })
  })
}

export default {
  name: 'GoodsSku',
  props: {
    goods: {
      type: Object,
      default: () => ({
        specs: [],
        skus: []
      })
    },
    skuId: {
      type: String,
      default: ''
    }
  },
  setup(props, context) {
    const changeSku = (btnObj, spec) => {
      if (btnObj.disabled) return
      if (btnObj.selected) {
        btnObj.selected = false
      } else {
        spec.values.forEach((btnObj) => (btnObj.selected = false))
        btnObj.selected = true
      }
      updateDisabledStatus(props.goods.specs, pathMap)

      const selectedSpecs = getSelectedSpec(props.goods.specs).filter((v) => v)
      if (selectedSpecs.length === props.goods.specs.length) {
        const key = selectedSpecs.join(spliter)
        const skuId = pathMap[key][0]
        const sku = props.goods.skus.find((sku) => sku.id === skuId)
        context.emit('change', {
          skuId: sku.id,
          price: sku.price,
          oldPrice: sku.oldPrice,
          inventory: sku.inventory,
          specsText: sku.specs
            .reduce((str, item) => `${str} ${item.name}：${item.valueName}`, '')
            .trim('')
        })
      } else {
        context.emit('change', {})
      }
    }
    initDefaultSelected(props.goods, props.skuId)
    const pathMap = getPathMap(props.goods.skus)
    updateDisabledStatus(props.goods.specs, pathMap)
    return { changeSku }
  }
}
</script>
<style scoped lang="less">
.sku-state-mixin () {
  border: 1px solid #e4e4e4;
  margin-right: 10px;
  cursor: pointer;
  &.selected {
    border-color: @xtxColor;
  }
  &.disabled {
    opacity: 0.6;
    border-style: dashed;
    cursor: not-allowed;
  }
}
.goods-sku {
  padding-left: 10px;
  padding-top: 20px;
  dl {
    display: flex;
    padding-bottom: 20px;
    align-items: center;
    dt {
      width: 50px;
      color: #999;
    }
    dd {
      flex: 1;
      color: #666;
      > img {
        width: 50px;
        height: 50px;
        .sku-state-mixin ();
      }
      > span {
        display: inline-block;
        height: 30px;
        line-height: 28px;
        padding: 0 20px;
        .sku-state-mixin ();
      }
    }
  }
}
</style>
